package com.tygz.controller;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.auto.base.pojo.SysModule;
import com.auto.base.pojo.SysRights;
import com.auto.base.pojo.SysRole;
import com.auto.base.pojo.SysUser;
import com.auto.base.service.SysModuleService;
import com.auto.base.service.SysRightsService;
import com.auto.base.service.SysRoleService;
import com.auto.base.service.SysUserService;
import com.auto.common.BaseController;
import com.auto.common.SessionInfo;
import com.auto.util.MyJsonConfig;
import com.base.common.CommonConstants;
import com.base.util.JUtil;
import com.tygz.pojo.SysModuleTree;
import com.tygz.util.JtargetUtil;


@Controller
@RequestMapping("/sys/Manage")
public class SysManageController extends BaseController {
	private final Logger log = LoggerFactory.getLogger(SysManageController.class);
	@Resource
	public  SysUserService service;
	@Resource
	public  SysRoleService sysRoleService;//角色实体表
	@Resource
	public  SysModuleService sysModuleService;//菜单模块实体表
	@Resource
	public  SysRightsService sysRightsService;//角色和菜单 关联中间表


	/**
	 * 登陆
	 * @param record
	 * @return
	 */
	@RequestMapping(value = "login")
	@ResponseBody
	public Object login( @ModelAttribute SysUser  record,HttpServletRequest request) {
		try {
			if(null == record){
				return setFail("接收数据为空！");
			}
			if(JUtil.isNull(record.getUserName())) {
				return setFail("用户名为空！");
			} 
			if(JUtil.isNull(record.getUserPassword())) {
				return setFail("用户密码为空！");
			} 
			SysUser queryUser = new SysUser();
			queryUser.setEnabled(CommonConstants.ENABLE);
			queryUser.setUserName(record.getUserName());
			queryUser = this.service.findSysUser(queryUser, null);
			Assert.notNull(queryUser, "该用户不存在！");
			Assert.notNull(queryUser.getUserPassword(), "该用户密码数据有问题！");

			if(!queryUser.getUserPassword().equals(record.getUserPassword())){
				return setFail("密码错误！");
			}
			//判断是否为超级管理员
			SessionInfo sessionInfo = new SessionInfo();
			sessionInfo.setSysUser(queryUser);
			if(JUtil.isNULL(queryUser.getUserType()) || queryUser.getUserType() != 0){
				//非超级管理员 需要得到他的权限信息
				//获取菜单的信息
				setAllowUrl(sessionInfo);
				//设置数据权限
				//setAccessToDataUserIds(sessionInfo);
			}else{
				//超级管理员
				List<SysModule> listAllSysModule = getAllSysModule();
				List<SysModuleTree>  moduleTree = JtargetUtil.getModuleTreegridData(listAllSysModule, 1);
				sessionInfo.setModuleList(JSONArray.fromObject(moduleTree, MyJsonConfig.JSON_CFG));
				String homeViewUrl = "/jsp/manage/index.jsp";
				JSONObject homeJson = JSONObject.fromObject(JtargetUtil.getHomeViewSysModuleTree(homeViewUrl), MyJsonConfig.JSON_CFG);
				sessionInfo.getModuleList().add(homeJson);
			}
			//获取分控用户 审批额度区间 以及产品类型

			JSONObject loginUser = JSONObject.fromObject(sessionInfo.getSysUser(),MyJsonConfig.JSON_CFG);

			sessionInfo.setLoginUser(loginUser);
			request.getSession().setAttribute(CommonConstants.SESSION_MANAGE_USER, sessionInfo);
			return setSuccess("登陆成功!");
		}catch(Exception e){
			log.error(e.getMessage(), e);
			return setFail("登陆异常!",e.getMessage());
		}
	}

	private List<SysModule> getAllSysModule() throws Exception{
		//个人首页设置
		//查找所有的模块
		SysModule querySysModule = new SysModule();
		querySysModule.setEnabled(CommonConstants.ENABLE);
		List<SysModule> listAllSysModule =  this.sysModuleService.listSysModule(querySysModule, null, null, null);
		return listAllSysModule;
	}

	//设置登录用户的访问页面权限的所有的url
	private void setAllowUrl(SessionInfo sessionInfo) throws Exception{
		//首先查询出用户关联的所有角色
		//	SysUser user = sessionInfo.getSysUser();
		Integer roleId = sessionInfo.getSysUser().getUserRole();
		if(JUtil.isNULL(roleId)){
			//throw new Exception("角色ID为空!");
			return;
		}
		SysRole queryRole  = new SysRole();
		queryRole.setEnabled(CommonConstants.ENABLE);
		queryRole.setId(roleId);
		queryRole = this.sysRoleService.findSysRole(queryRole, null);
		if(JUtil.isNULL(queryRole)){
			//throw new Exception("角色信息不存在!");
			return;
		}
		//sessionInfo.setSysRole(queryRole);//设置角色信息到session中
		sessionInfo.getSysUser().setUserRoleName(queryRole.getRoleName());

		//查找所有的模块
		List<SysModule> listAllSysModule = getAllSysModule();
		if(null == listAllSysModule || listAllSysModule.isEmpty()){
			return;
		}

		SysRights querySysRights = new SysRights();
		querySysRights.setEnabled(CommonConstants.ENABLE);
		querySysRights.setRoleId(roleId);
		List<SysRights> listSysRights = this.sysRightsService.listSysRights(querySysRights, null, null, null);
		if(null == listSysRights || listSysRights.isEmpty() ){
			return;
		}

		//查找模块
		List<SysModule> listSysModule = new ArrayList<SysModule>();//存储模块列表 可以用于菜单json生成
		//便利查找所有匹配的SysModule
		for(SysModule sm:listAllSysModule){
			Integer moduleId = sm.getId();
			String url = sm.getModuleUrl();
			for(SysRights sr:listSysRights){
				if(!JUtil.isNULL(sr.getModuleId()) && (moduleId == sr.getModuleId())){
					//匹配到
					if(!JUtil.isNull(url)  && !"/".equals(url)){
						sessionInfo.getAllowUrl().add(url.replace("/", ""));
					}
					listSysModule.add(sm);
				}
			}
		}

		if(null!=listSysModule && !listSysModule.isEmpty()){
			List<SysModuleTree>  moduleTree = JtargetUtil.getModuleTreegridData(listSysModule, 1);
			sessionInfo.setModuleList(JSONArray.fromObject(moduleTree, MyJsonConfig.JSON_CFG));
		}
		
		String homeViewUrl = "/jsp/manage/index.jsp";
		//加入到权限过滤器中
		sessionInfo.getAllowUrl().add(homeViewUrl.replace("/", ""));
		
		JSONObject homeJson = JSONObject.fromObject(JtargetUtil.getHomeViewSysModuleTree(homeViewUrl), MyJsonConfig.JSON_CFG);
		sessionInfo.getModuleList().add(homeJson);

	}

	/**
	 * 注销
	 * @param record
	 * @return
	 */
	@RequestMapping(value = "logout")
	@ResponseBody
	public Object logout( @ModelAttribute SysUser  record,HttpServletRequest request) {
		try {
			JUtil.setSessionNull(request);
			return setSuccess("注销成功!");
		}catch(Exception e){
			log.error(e.getMessage(), e);
			return setFail("注销异常!",e.getMessage());
		}
	}

}
